package com.example.drive.fragment

import com.example.drive.base.BaseFragment
import com.example.drive.bean.ResultBean
import android.view.LayoutInflater
import android.os.Bundle
import android.graphics.BitmapFactory
import android.text.Html
import android.text.TextUtils
import android.view.View
import com.example.drive.R
import android.widget.RadioGroup
import androidx.lifecycle.lifecycleScope
import com.example.drive.DrivingAnswer
import com.example.drive.bean.DrivingAnswerBean
import com.example.drive.databinding.FragmentQuestionBinding
import com.example.drive.db.JZTKDataBase
import com.example.drive.net.asyncRequest
import com.example.drive.net.callback.ByteArrayCallback
import com.example.drive.net.request.GetRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 答题Fragment
 */
class QuestionFragment : BaseFragment<FragmentQuestionBinding>() {
    companion object {
        private const val KEY_RESULT_BEAN = "key_result_bean"
        private const val KEY_MY_ANSWER = "key_my_answer"

        /**
         * 创建一个答题Fragment
         *
         * @param resultBean 题目信息
         * @param myAnswer   我的回答(用于恢复状态)
         * @return 答题Fragment
         */
        fun newInstance(resultBean: ResultBean, myAnswer: String?): QuestionFragment {
            val args = Bundle()
            val fragment = QuestionFragment()
            args.putParcelable(KEY_RESULT_BEAN, resultBean)
            args.putString(KEY_MY_ANSWER, myAnswer)
            fragment.arguments = args
            return fragment
        }
    }

    // 映射关系请查看assets目录文件:answer字段对应答案
    private val judgeMap: Map<String, String> by lazy {
        mutableMapOf("1" to "正确", "2" to "错误")
    }
    private val singleChoiceMap: Map<String, String> by lazy {
        mutableMapOf("1" to "A", "2" to "B", "3" to "C", "4" to "D")
    }
    private lateinit var resultBean: ResultBean
    private var myAnswer: String? = null

    override fun initViewBinding(inflater: LayoutInflater): FragmentQuestionBinding {
        return FragmentQuestionBinding.inflate(inflater)
    }

    override fun initData() {
        arguments?.let {
            resultBean = it.getParcelable(KEY_RESULT_BEAN)!!
            myAnswer = it.getString(KEY_MY_ANSWER, "")
            val question = resultBean.question
            binding?.tvQuestion?.text = question
            loadImage()
            val item1 = resultBean.item1
            val item2 = resultBean.item2
            val item3 = resultBean.item3
            val item4 = resultBean.item4
            val answer: String?
            if (TextUtils.isEmpty(item4)) {
                // 判断题
                binding?.radioButton1?.text = item1
                binding?.radioButton2?.text = item2
                binding?.radioButton3?.visibility = View.GONE
                binding?.radioButton4?.visibility = View.GONE
                answer = judgeMap[resultBean.answer]
            } else {
                // 单选题
                binding?.radioButton1?.text = "A $item1"
                binding?.radioButton2?.text = "B $item2"
                binding?.radioButton3?.text = "C $item3"
                binding?.radioButton4?.text = "D $item4"
                binding?.radioButton3?.visibility = View.VISIBLE
                binding?.radioButton4?.visibility = View.VISIBLE
                answer = singleChoiceMap[resultBean.answer]
            }
            binding?.tvAnswer?.text = answer
            val explains = resultBean.explains
            // Html.fromHtml(),避免文本中有<br/>
            binding?.tvExplains?.text = Html.fromHtml(explains, Html.FROM_HTML_MODE_COMPACT)
            binding?.llAnswer?.setOnClickListener {
                binding?.tvCheckAnswer?.text = "答案:"
                binding?.tvAnswer?.visibility = View.VISIBLE
                binding?.tvExplains?.visibility = View.VISIBLE
            }
            judgeAnswer()
        }
    }

    // 加载图片
    private fun loadImage() {
        val url = resultBean.url
        if (url == null || url.isEmpty()) {
            binding?.imageView?.visibility = View.GONE
        } else {
            binding?.imageView?.visibility = View.VISIBLE

            // 如果仅加载图片,使用BitmapCallback更便捷
            /*GetRequest(url ?: "").asyncRequest(object : BitmapCallback() {
                override fun onResponse(data: Bitmap?) {
                    data?.let {
                        binding?.imageView?.setImageBitmap(it)
                    }
                }

                override fun onFailure(throwable: Throwable) {

                }
            })*/

            val bytes = resultBean.file
            if (bytes == null || bytes.isEmpty()) {
                // 加载网络图片
                GetRequest(url).asyncRequest(object : ByteArrayCallback() {
                    override fun onResponse(data: ByteArray?) {
                        data?.let {
                            val bitmap = BitmapFactory.decodeByteArray(it, 0, it.size)
                            binding?.imageView?.setImageBitmap(bitmap)
                            // 将data存至数据库,下次优先从数据库加载图片
                            lifecycleScope.launch(Dispatchers.IO) {
                                resultBean.file = data
                                JZTKDataBase.resultBeanDao.update(resultBean)
                            }
                        }
                    }

                    override fun onFailure(throwable: Throwable) {

                    }
                })
            } else {
                // 加载本地图片
                val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                binding?.imageView?.setImageBitmap(bitmap)
            }
        }
    }

    // 判断做题情况(没有答题、答题正确、答题错误)
    private fun judgeAnswer() {
        val resultBeanAnswer = resultBean.answer
        binding?.radioGroup?.setOnCheckedChangeListener { _: RadioGroup?, id: Int ->
            var myAnswer = ""
            when (id) {
                R.id.radioButton1 -> {
                    myAnswer = "1"
                }
                R.id.radioButton2 -> {
                    myAnswer = "2"
                }
                R.id.radioButton3 -> {
                    myAnswer = "3"
                }
                R.id.radioButton4 -> {
                    myAnswer = "4"
                }
            }
            val drivingAnswer = if (TextUtils.equals(resultBeanAnswer, myAnswer)) {
                DrivingAnswer.RIGHT
            } else {
                DrivingAnswer.WRONG
            }
            val mainFragment = parentFragment as? MainFragment
            mainFragment?.putAnswer(resultBean.id!!, drivingAnswer)
            // 将题次和对应的回答保存到数据库,下次进来恢复状态
            lifecycleScope.launch(Dispatchers.IO) {
                JZTKDataBase.drivingAnswerBeanDao.insert(DrivingAnswerBean().apply {
                    this.id = resultBean.id
                    this.myAnswer = myAnswer
                })
            }
        }
        recoverMyAnswer()
    }

    private fun recoverMyAnswer() {
        when (myAnswer) {
            "1" -> binding?.radioButton1?.isChecked = true
            "2" -> binding?.radioButton2?.isChecked = true
            "3" -> binding?.radioButton3?.isChecked = true
            "4" -> binding?.radioButton4?.isChecked = true
            else -> {}
        }
    }
}